package com.lw.leetcode.dp.b;

/**
 * 97. 交错字符串
 * b
 * db
 *
 * @Author liw
 * @Date 2021/5/31 11:28
 * @Version 1.0
 */
public class IsInterleave {

    public static void main(String[] args) {
        IsInterleave test = new IsInterleave();
        // true
//        String s1 = "aabcc";
//        String s2 = "dbbca";
//        String s3 = "aadbbcbcac";

        // false
//        String s1 = "aabcc";
//        String s2 = "dbbca";
//        String s3 = "aadbbbaccc";

        // true
        String s1 = "aabc";
        String s2 = "abad";
        String s3 = "aabadabc";

        // false
//        String s1 = "db";
//        String s2 = "b";
//        String s3 = "cbb";

        // false
//        String s1 = "";
//        String s2 = "abc";
//        String s3 = "abc";


        boolean interleave = test.isInterleave(s1, s2, s3);
        System.out.println(interleave);
    }


    // 自己的方法 6ms  36.7MB
    public boolean isInterleave(String s1, String s2, String s3) {
        int a = s1.length();
        int b = s2.length();
        if (a + b != s3.length()) {
            return false;
        }
        boolean[] arr = new boolean[b + 1];
        for (int i = 0; i < b; i++) {
            if(s2.charAt(i) == s3.charAt(i)) {
                arr[i + 1] = true;
            } else {
                break;
            }
        }
        arr[0] = true;
        for (int i = 1; i <= a; i++) {
            arr[0] = arr[0] && s1.charAt(i - 1) == s3.charAt(i - 1);
            for (int j = 1; j <= b; j++) {
                char c = s3.charAt(i + j - 1);
                arr[j] = (arr[j] && s1.charAt(i - 1) == c || (arr[j - 1] && s2.charAt(j - 1) == c));
            }
        }
        return arr[b];
    }

    // 复制评论的方法， 4ms  36.4MB
    public boolean isInterleave2(String s1, String s2, String s3) {
        int s1len = s1.length();
        int s2len = s2.length();
        int s3len = s3.length();

        if (s1len + s2len != s3len) {
            return false;
        }

        boolean[][] dp = new boolean[s1len + 1][s2len + 1];

        dp[0][0] = true;
        for (int i = 1; i <= s1len && (dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1)); i++) {
            dp[i][0] = true;
        }
        for (int i = 1; i <= s2len && (dp[0][i - 1] && s2.charAt(i - 1) == s3.charAt(i - 1)); i++) {
            dp[0][i] = true;
        }

        for (int i = 1; i <= s1len; i++) {
            for (int j = 1; j <= s2len; j++) {
                char c = s3.charAt(i + j - 1);
                dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == c) || (dp[i][j - 1] && s2.charAt(j - 1) == c);
            }
        }
        return dp[s1len][s2len];
    }
}
